package com.rain.lo.controller;

import com.rain.lo.common.Constants;
import com.rain.lo.common.utils.HttpUtil;
import com.rain.lo.common.utils.ResultUtil;
import com.rain.lo.entity.User;
import com.rain.lo.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {

    @Resource
    private UserService userService;

    @RequestMapping("login.html")
    public String toLogin(){
        return "login";
    }

    @ResponseBody
    @RequestMapping("login")
    public Object login(String username,String password){
        if (username.isEmpty() || password.isEmpty()){
            return ResultUtil.toFailResult("用户名或密码不能为空！");
        }
        User user=null;
        /*if (StringUtil.isMobile(username) ) {
             user = userService.queryUserByMobile(username);
        }else
            user = userService.queryUserByName(username);暂不启用*/
        user = userService.queryUserByName(username);
        if (user==null){
            return ResultUtil.toFailResult("用户不存在！");
        }

        if (!user.getPassword().equals(DigestUtils.md5Hex(password+ Constants.PASSWORD_SOLT))){
            return ResultUtil.toFailResult("密码错误！");
        }

        HttpSession httpSession = HttpUtil.getSession();
        httpSession.setAttribute("user",user);
        return ResultUtil.toSuccResult();
    }

    @ResponseBody
    @RequestMapping("list/user")
    public Object list(Long row,Long num){
        List<User> list = userService.list(row,num);
        long count = userService.count();
        return ResultUtil.toResult(list,count);
    }

    @RequestMapping("user.html")
    public String showSignup(){
        return "user";
    }

}
